<?php

namespace Rebecca\CustomGeneratorBundle\Generator;

use Sensio\Bundle\GeneratorBundle\Generator\DoctrineCrudGenerator;
use Rebecca\CustomGeneratorBundle\Manipulator\ServicesManipulator;
use Symfony\Component\HttpKernel\Util\Filesystem;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;

/**
 * Description of RebecaDoctrineCrudGenerator
 *
 * @author JeyDotC
 */
class RebecaDoctrineCrudGenerator extends DoctrineCrudGenerator {

    /**
     * A shadow copy of skeletonDir :p
     * @var string
     */
    private $templatesDir;

    public function __construct(Filesystem $filesystem, $skeletonDir) {
        parent::__construct($filesystem, $skeletonDir);
        $this->templatesDir = $skeletonDir;
    }

    public function generate(BundleInterface $bundle, $entity,
            ClassMetadataInfo $metadata, $format, $routePrefix,
            $needWriteActions) {
        parent::generate($bundle, $entity, $metadata, $format, $routePrefix, $needWriteActions);
        $this->generateComponentClass($bundle, $entity);
        $this->generateServiceDeclaration($bundle, $entity);
    }


    private function generateComponentClass(BundleInterface $bundle, $entity) {
        $dir = $bundle->getPath();

        $parts = explode('\\', $entity);
        $entityClass = array_pop($parts);
        $entityNamespace = implode('\\', $parts);

        $target = sprintf(
                '%s/Component/%s/%sComponent.php', $dir, str_replace('\\', '/', $entityNamespace), $entityClass
        );

        if (file_exists($target)) {
            throw new \RuntimeException('Unable to generate the component as it already exists.');
        }

        $this->renderFile($this->templatesDir, 'component.php', $target, array(
            'entity' => $entity,
            'entity_class' => $entityClass,
            'namespace' => $bundle->getNamespace(),
            'entity_namespace' => $entityNamespace,
        ));
    }

    private function generateServiceDeclaration(BundleInterface $bundle, $entity) {
        $file = $bundle->getPath() . "/Resources/config/services.yml";
        $manipulator = new ServicesManipulator($file);
        $parts = explode('\\', $entity);
        $entityClass = array_pop($parts);
        $entityNamespace = implode('\\', $parts);

        $entity_namespace = $entityNamespace ? "\\$entityNamespace" : "";
        $component = "{$bundle->getNamespace()}\Component$entity_namespace\\{$entityClass}Component";

        $manipulator->addService($bundle->getName(), $entity, $component);
    }

}

?>
